package main

import (
	"fmt"
	httptransport "github.com/go-kit/kit/transport/http"
	mymux "github.com/gorilla/mux"
	logging "github.com/sirupsen/logrus"
	"golang.org/x/time/rate"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	service "webdemo/src/go-kit/service"
	"webdemo/src/go-kit/utils"
)

func main() {
	//go get golang.org/x/time/rate
	//每秒产生个数  最大个数
	limiter := rate.NewLimiter(1, 3)

	// go run server.go -name go-kit -p 8080
	//读取命令行参数
	/*registrationName := flag.String("name","","服务名称")
	port := flag.Int("p", 0, "端口号")
	if *registrationName == "" {
		log.Fatal("请输入服务名")
	}
	if *port == 0 {
		log.Fatal("请输入服务端口号")
	}
	utils.SetServiceInfo(*registrationName,*port)*/

	userService := service.UserService{}

	// 限流
	// 加入 限流中间件
	endpoint := service.RateLimit(limiter)(service.GenUserEndpoint(userService))
	//endpoint := service.GenUserEndpoint(userService)

	// 统一异常处理
	options := []httptransport.ServerOption{
		httptransport.ServerErrorEncoder(service.MyErrorEncoder),
	}

	server := httptransport.NewServer(endpoint, service.DecodeUserRequest, service.EncodeUserRequest, options...)
	// http.ListenAndServe(":8080",server)

	router := mymux.NewRouter()
	//router.Handle("/user/{uid}",server)
	{
		router.Methods("GET", "DELETE").Path("/user/{uid}").Handler(server)

		router.Methods("GET").Path("/").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
			writer.Header().Set("Content-Type", "application/json")
			writer.Write([]byte(`{"status":"ok"}`))
		})
	}

	errChan := make(chan error)
	go func() {
		// 注册服务
		utils.ConsulRegister()

		err := http.ListenAndServe(":8080", router)
		if err != nil {
			logging.Error(err)
			errChan <- err
		}
	}()

	go func() {
		// 取消注册
		sig_c := make(chan os.Signal)
		// 信号监听，优雅停机
		signal.Notify(sig_c, syscall.SIGINT, syscall.SIGTERM)

		errChan <- fmt.Errorf("%s", <-sig_c)
	}()

	getErr := <-errChan
	utils.ConsulCancelRegister()
	logging.Error(getErr)

}
